const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { failureResponse, successResponse } = require('../utils/responses');
const { NotFoundError, BadRequestError } = require('../utils/errors')
const bcrypt = require('bcrypt');

// 查询当前登录用户
router.get('/me', async function(req, res, next) {
  try {
    const user = await getUser(req)
    successResponse(res, '查询当前用户信息成功', { user });
  } catch (error) {
    failureResponse(res, error);
  }
});

// 更新当前用户信息
router.put('/info', async function(req, res, next) {
  try {
    const body = {
      nickname: req.body.nickname,
      sex: req.body.sex,
      company: req.body.company,
      introduce: req.body.introduce,
      avatar: req.body.avatar
    }
    const user = await getUser(req);
    await user.update(body);
    successResponse(res, '更新当前用户信息成功', { user });
  } catch (error) {
    failureResponse(res, error);
  }
});

// 更新用户账号
router.put('/account', async function(req, res, next) {
  try {
    const body = {
      email: req.body.email,
      username: req.body.username,
      current_password: req.body.current_password, // 当前密码
      password: req.body.password, // 新密码
      passwordConfirmation: req.body.passwordConfirmation
    }
    if (!body.current_password) {
      throw new BadRequestError('当前密码必须填写');
    }
    if (body.password !== body.passwordConfirmation) {
      throw new BadRequestError('两次输入的密码不一致');
    }
    const user = await getUser(req, true);
    const isPasswordValid = bcrypt.compareSync(body.current_password, user.password);
    if (!isPasswordValid) {
      throw new BadRequestError('当前密码不正确');
    }
    await user.update(body)
    delete user.dataValues.password
    successResponse(res, '更新当前用户账号成功', { user });
  } catch (error) {
    failureResponse(res, error);
  }
});

async function getUser(req, showPassword = false) {
  const userId = req.userId;
  let condition = {}
  if (!showPassword) {
    condition = {
      attributes: { exclude: ['password'] }
    }
  }
  const user = await User.findByPk(userId, condition);
  if (!user){
    throw new NotFoundError(`ID: ${userId} 的用户不存在`);
  }
  return user;
}

module.exports = router;
